//
//  ACAudienceViewController.m
//  ACLiteAVUISDK
//
//  Created by 冯琰琰 on 2021/3/29.
//

#import "ACAudienceViewController.h"
#import "JXCategoryView.h"
#import "ACLiveIntroductionViewController.h"
#import "ACLiveFileListViewController.h"
#import "ACLiveChatAudienceViewController.h"
#import "ACLiveMemberListViewController.h"
#import "ACAnchorViewController.h"
#import "ACAnchorViewController+LiveDelegate.h"
#import "ACAudienceViewController+LiveDelegate.h"
#import "ACLiveModel.h"

@interface ACAudienceViewController ()<JXCategoryViewDelegate,JXCategoryListContainerViewDelegate>
{
    UIImageView *topBgView;
    UIButton *closeBtn;
    
}
@property (nonatomic, strong) JXCategoryTitleView *myCategoryView;
@property (nonatomic, strong) JXCategoryBaseView *categoryView;
@property (nonatomic, strong) JXCategoryListContainerView *listContainerView;
@property (nonatomic, strong)UIView *writeBoardView;
@property (nonatomic, strong) NSArray *titles;
@property(nonatomic,assign)NSInteger selectedIndex;
@property(nonatomic,strong)TRTCCloudAnction *trtcAction;
@property(nonatomic,strong)ACLiveChatAudienceViewController *ChatVC;
@property(nonatomic,strong)ACLiveFileListViewController *filelistVC;
@property(nonatomic,strong)UILabel *liveTitle;

@end

@implementation ACAudienceViewController
-(void)setLiveRoom:(TRTCLiveRoom *)liveRoom{
    _liveRoom = liveRoom;
    self.ChatVC.liveRoom = liveRoom;
}
-(void)setLiveID:(NSString *)liveID{
    _liveID = liveID;
    self.filelistVC.liveID = liveID;
    self.ChatVC.liveID = liveID;
}
- (TRTCLiveUserInfo *)anchor{
    if (!_anchor) {
        _anchor = [[TRTCLiveUserInfo alloc]init];
    }
    return _anchor;
}
-(UIView *)writeBoardView{
    if (!_writeBoardView) {
        _writeBoardView = [[UIView alloc] init];
    }
    return _writeBoardView;
}
-(void)resetSpeakerBtnStatus{
    [self.ChatVC resetStatus];
}
-(void)resetSpeakerBtnStatusLinkMic{
    [self.ChatVC setStatusLinkMic];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.categoryView];
    [self.view addSubview:self.listContainerView];
    
    self.ChatVC = [[ACLiveChatAudienceViewController alloc] init];
    self.ChatVC.liveRoom = self.liveRoom;
    self.ChatVC.liveID = self.liveID;
    @weakify(self)
    self.ChatVC.requestJoinMicHandler = ^(NSString * _Nonnull userID, BOOL isCancel) {
      // 请求连麦的人
        @strongify(self)
        if (isCancel) {
            // 取消发言
            [self.liveRoom quitJoinAnchor:self.liveModel.created_by callback:^(int code, NSString * _Nullable message) {
                [SVProgressHUD showInfoWithStatus:@"我取消了发言"];
            }];
        }else{
            [self.liveRoom requestJoinAnchor:self.liveModel.created_by responseCallback:^(BOOL agreed, NSString * _Nullable reason) {
//                [SVProgressHUD showInfoWithStatus:@"我申请了发言"];
            }];
//            [ACLiveRoomManager requestToAskWithLiveID:self.liveID requestCallback:^(int code, NSString * _Nullable message) {
//
//            }];
        }
    };
    
    self.filelistVC = [[ACLiveFileListViewController alloc] init];
    self.filelistVC.liveID = self.liveID;
    
    self.remoteVideoView = [[UIView alloc] init];
    [self.view addSubview:self.remoteVideoView];
    [self.remoteVideoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(ACStatusBarHeight);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(ACSCREEN_WIDTH * 9.0 / 16.0);
    }];
    
    topBgView = [[UIImageView alloc]initWithImage: [UIImage imageWithName:@"icon_live_room_bg" bundle:ACLiteAVUISDK targetClass:[self class]]];
    topBgView.userInteractionEnabled = YES;
    [self.view addSubview:topBgView];
    [topBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(0);
        make.height.mas_equalTo(48 + ACStatusBarHeight);
    }];
    
    self.liveTitle = [[UILabel alloc] init];
    self.liveTitle.text = @"";
    self.liveTitle.textAlignment = NSTextAlignmentCenter;
    self.liveTitle.textColor = UIColorFromRGB(0xffffff);
    self.liveTitle.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    [topBgView addSubview:self.liveTitle];
    [self.liveTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(topBgView.mas_bottom).offset(-10);
        make.left.mas_equalTo(50);
        make.right.mas_equalTo(-60);
    }];
    
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [closeBtn setImage:[UIImage imageWithName:@"icon_live_room_close" bundle:ACLiteAVUISDK targetClass:[self class]] forState:UIControlStateNormal];
    [self.view addSubview:closeBtn];
    [closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(28, 28));
        make.bottom.equalTo(topBgView.mas_bottom).offset(-10);
        make.right.equalTo(topBgView.mas_right).offset(-15);
    }];
    [[closeBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        [self exitLiveRoom];
    }];
    
    self.fd_prefersNavigationBarHidden = YES;
    self.fd_interactivePopMaxAllowedInitialDistanceToLeftEdge = 200;
    
    self.titles = [[NSArray alloc] initWithObjects:@"简介",@"文档", @"互动",@"人员", nil];
    self.myCategoryView.titles = self.titles;
    self.myCategoryView.titleColor = UIColorFromRGB(0x909399);
    self.myCategoryView.titleSelectedColor = UIColorFromRGB(0xFF6048);
    self.myCategoryView.titleFont = [UIFont systemFontOfSize:14];
    self.myCategoryView.titleSelectedFont = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
    self.myCategoryView.titleLabelMaskEnabled = YES;
    self.myCategoryView.defaultSelectedIndex = 0;
    
    JXCategoryIndicatorLineView *lineView = [[JXCategoryIndicatorLineView alloc] init];
    lineView.indicatorWidth = JXCategoryViewAutomaticDimension;
    self.myCategoryView.indicators = @[lineView];
    self.myCategoryView.titleColorGradientEnabled = YES;
    [self.myCategoryView removeFromSuperview];
   
    [self.view addSubview:self.myCategoryView];
    [self.myCategoryView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(40);
        make.top.mas_equalTo(ACSCREEN_WIDTH * 9.0 / 16.0 + ACStatusBarHeight);
    }];
    
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = UIColorFromRGB(0xE2E1E0);
    [self.view addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.equalTo(self.categoryView.mas_bottom);
        make.height.mas_equalTo(0.5);
    }];
    
    [self.listContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.mas_equalTo(0);
        make.top.equalTo(line.mas_bottom);
    }];
}
- (void)showWriteBoardViewWithuserID:(NSString *)userID{
    [self.view insertSubview:self.writeBoardView atIndex:0];
    [self.writeBoardView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(ACStatusBarHeight);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(ACSCREEN_WIDTH * 9.0 / 16.0);
    }];
    [self.remoteVideoView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right).offset(-10);
        make.top.mas_equalTo(ACStatusBarHeight);
        make.width.mas_equalTo(160);
        make.height.mas_equalTo(90);
    }];
    [self.liveRoom startRemoteView:userID View:self.writeBoardView];
}
-(void)removeWriteBoardViewWithuserID:(NSString *)userID{
    [self.writeBoardView removeFromSuperview];
    NSArray *array = [MASViewConstraint installedConstraintsForView:self.writeBoardView];
    for (MASConstraint *constraint in array) {
        [constraint uninstall];
    }
    [self.remoteVideoView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(ACStatusBarHeight);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(ACSCREEN_WIDTH * 9.0 / 16.0);
    }];
    [self.liveRoom stopRemoteView:userID];
}
- (void)requestLiveInfo{
    [SVProgressHUD showWithStatus:@""];
    [ACLiveRoomManager requestLiveDetailWithLiveID:self.liveID success:^(id  _Nonnull responseObject) {
        self.liveModel = [ACLiveModel mj_objectWithKeyValues:responseObject];
        self.liveTitle.text = self.liveModel.title;
        [SVProgressHUD dismiss];
        NSDictionary *dic = [self.listContainerView validListDict];
        ACLiveIntroductionViewController *introductionVC = [dic objectForKey:[NSNumber numberWithInteger:0]];
        introductionVC.liveModel = self.liveModel;
    } failure:^(NSError * _Nonnull error) {
        [SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
    }];
}
- (void)enterInviteAnchor{
    @weakify(self)
    [self.liveRoom exitRoom:^(int code, NSString * _Nullable message) {
        @strongify(self)
        DDLogInfo(@"---exitRoom---code-----%d----message-------%@",code,message);
        if (code == 0) { // 退出房间成功 跳转页面
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                ACAnchorViewController *anchorVC = [[ACAnchorViewController alloc] init];
                [self.navigationController pushViewController:anchorVC animated:YES];
                [anchorVC loginWithRoomID:self.liveID isAnchor:YES isOwner:NO callback:^(int code, NSString * _Nullable message) {
                    
                }];
                [anchorVC.backSubject subscribeNext:^(id  _Nullable x) {
                    [self enterLiveRoom];
                } completed:^{

                }];
            });
        }
    }];
}
-(void)enterLiveRoom{
    [self loginWithRoomID:self.liveID callback:^(int code, NSString * _Nullable message) {
        
    }];
}
- (void)exitLiveRoom{
    [self.liveRoom exitRoom:^(int code, NSString * _Nullable message) {
        DDLogInfo(@"---exitRoom---code-----%d----message-------%@",code,message);
    }];
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)bulletNewMsg:(ACMsgModel *)msgModel{
    [self.ChatVC bulletNewMsg:msgModel];
}

#pragma mark - JXCategoryViewDelegate
// 点击选中或者滚动选中都会调用该方法。适用于只关心选中事件，不关心具体是点击还是滚动选中的。
- (void)categoryView:(JXCategoryBaseView *)categoryView didSelectedItemAtIndex:(NSInteger)index {
    DDLogInfo(@"%@", NSStringFromSelector(_cmd));
    // 侧滑手势处理
    self.navigationController.interactivePopGestureRecognizer.enabled = (index == 0);
}

// 滚动选中的情况才会调用该方法
- (void)categoryView:(JXCategoryBaseView *)categoryView didScrollSelectedItemAtIndex:(NSInteger)index {
    DDLogInfo(@"%@", NSStringFromSelector(_cmd));
}

#pragma mark - JXCategoryListContainerViewDelegate
// 返回列表的数量
- (NSInteger)numberOfListsInlistContainerView:(JXCategoryListContainerView *)listContainerView {
    return self.titles.count;
}

// 返回各个列表菜单下的实例，该实例需要遵守并实现 <JXCategoryListContentViewDelegate> 协议
- (id<JXCategoryListContentViewDelegate>)listContainerView:(JXCategoryListContainerView *)listContainerView initListForIndex:(NSInteger)index {
    if (index == 0) {
        NSBundle *curB = [NSBundle BundleWithBundleName:ACLiteAVUISDK targetClass:[self class] ];
        ACLiveIntroductionViewController *VC = [[ACLiveIntroductionViewController alloc] initWithNibName:@"ACLiveIntroductionViewController" bundle:curB];
        return VC;
    }else if (index == 1){
        self.filelistVC.index = 2;
        return self.filelistVC;
    }else if(index == 2){
        return self.ChatVC;
    }else{
        ACLiveMemberListViewController *VC = [[ACLiveMemberListViewController alloc] init];
        return VC;
    }
}
// 分页菜单视图
- (JXCategoryBaseView *)categoryView {
    if (!_categoryView) {
        _categoryView = [self preferredCategoryView];
        _categoryView.delegate = self;
        _categoryView.listContainer = self.listContainerView;
    }
    return _categoryView;
}
-(JXCategoryTitleView *)myCategoryView{
    return (JXCategoryTitleView *)self.categoryView;;
}
- (JXCategoryBaseView *)preferredCategoryView {
    return [[JXCategoryTitleView alloc] init];
}
// 列表容器视图
- (JXCategoryListContainerView *)listContainerView {
    if (!_listContainerView) {
        _listContainerView = [[JXCategoryListContainerView alloc] initWithType:JXCategoryListContainerType_ScrollView delegate:self];
    }
    return _listContainerView;
}

@end
